<?php

namespace App\Repositories;

use App\Models\Product;
use App\Models\ProductSku;
use App\Models\ProductImage;
use App\Repositories\ProductSkuRepo;

use App\Exceptions\InvalidException;
use DB;
use Log;
use Illuminate\Support\Facades\Redis;

class ProductRepo
{
    const PRODUCT_INFO_KEY = "product:info:{id}";

    public function getProductInfoKey($id)
    {
        return str_replace("{id}", $id, self::PRODUCT_INFO_KEY);
    }

    public function test()
    {
        var_dump('test');
    }

    public function delProducts($ids)
    {
        try {
            Product::whereIn('id', $ids)->update(['is_able' => -1]);
        } catch (\Exception $e) {
            throw InvalidException($e->getMessage());
        }
    }

    public function getProductList($where = [], $pageSize = 10)
    {

        $products = Product::where(function ($query) use ($where) {
            if (!empty($where['is_able'])) {
                $query->where('is_able', $where['is_able']);
            }
        })->select('id', 'name', 'desc', 'tip', 'price', 'image', 'status', 'is_recommend', 'is_able')->paginate($pageSize);
        return $products;
    }

    public function addProduct(array $data, $imgList = [], $specList = [])
    {
        // var_dump($data);
        $main_data = [
            'name' => $data['name'],
            'cate_id' => $data['cate_id'],
            'image' => $data['image'],
            'desc' => $data['desc'],
            'store' => $data['store'],
            'tip' => $data['tip'] ?? '',
            'price' => $data['price'],
            'content' => $data['content'],
            'spec_type' => $data['spec_type'],
            'attr' => is_array($data['attr']) ? json_encode($data['attr']) : $data['attr']
        ];
        DB::beginTransaction();
        try {
            $product = Product::create($main_data);
            if (!empty($imgList)) {

                $imgData = [];
                foreach ($imgList as $img) {
                    $imgData[] = ['product_id' => $product->id, 'url' => $img['url']];
                }
                ProductImage::insert($imgData);
            }
            if ($data['spec_type'] == 1 && !empty($data['skus'])) {
                foreach ($data['skus'] as &$item) {
                    $item['product_id'] = $product->id;
                }
                $productSku = new ProductSkuRepo();
                //多规格商品
                $productSku->create($product->id, $data['skus']);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            throw new InvalidException($e->getMessage());
        }
    }

    public function editProduct($id, array $data, $imgList = [], $specList = [])
    {
        $product = Product::where('id', $id)->first();

        if (!$product) {
            throw new InvalidException("商品不存在");
        }
        $main_data = [
            'name' => $data['name'],
            'cate_id' => $data['cate_id'],
            'image' => $data['image'],
            'desc' => $data['desc'],
            'price' => $data['price'],
            'store' => $data['store'],
            'content' => $data['content'],
            'spec_type' => $data['spec_type'],
            'attr' => json_encode($data['attr']),
        ];
        DB::beginTransaction();
        try {
            $product->update($main_data);
            //更新
            if (!empty($imgList)) {
                ProductImage::where('product_id', $product->id)->delete();
                $imgData = [];
                foreach ($imgList as $img) {
                    if (isset($img['percentage']) && $img['percentage'] == 100) {
                        continue;
                    }
                    $imgData[] = ['product_id' => $id, 'url' => $img['url']];
                }
                ProductImage::insert($imgData);
            }
            if ($main_data['spec_type'] == 1 && !empty($data['skus'])) {
                $productSku = new ProductSkuRepo();
                //多规格商品
                $productSku->edit($id, $data['skus']);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e->getMessage());
            throw new InvalidException("更新失败");
        }

    }

    /***
     * @param $id
     * @return mixed
     * @throws InvalidException
     */
    public function getOneProduct($id): mixed
    {
        $keyId = $this->getProductInfoKey($id);

        $product = Product::where('id', $id)->first()->toArray();
        if (!$product) {
            throw new InvalidException("产品不存在");
        }
        $product['images'] = [];
        if (!$product) {
            throw new InvalidException("商品不存在");
        } else {
            $imgList = ProductImage::where('product_id', $id)->select('url')->get()->toArray();
            if ($imgList) {
                $product['images'] = $imgList;
            }
            $product['spec_list'] = ProductSku::where('product_id', $id)->get();
        }
        return $product;
    }

    /***
     * @param $id
     * @return void
     * @throws InvalidException
     * @descript 上架产品
     */
    public function setUp($id): void
    {
        $product = Product::where('id', $id)->first();

        if (!$product) {
            throw new InvalidException("产品不存在");
        }
        $product->status = 1;
        $product->save();
    }

    /***
     * @param $id
     * @return void
     * @throws InvalidException
     * @descript  下架产品
     */
    public function setDown($id): void
    {
        $product = Product::where('id', $id)->first();

        if (!$product) {
            throw new InvalidException("产品不存在");
        }
        $product->status = 2;
        $product->save();
    }

    /***
     * @param $id
     * @return void
     * @throws InvalidException
     * @descript  设置为推荐
     */
    public function setRecommend($id)
    {
        $product = Product::where('id', $id)->first();

        if (!$product) {
            throw new InvalidException("产品不存在");
        }
        $product->is_recommend = 1;
        $product->save();
    }

    /***
     * @param $id
     * @return void
     * @throws InvalidException
     * @descript  设置为不推荐
     */
    public function setUnRecommend($id)
    {
        $product = Product::where('id', $id)->first();

        if (!$product) {
            throw new InvalidException("产品不存在");
        }
        $product->is_recommend = 0;
        $product->save();

    }

    public function getRecommend()
    {
        return Product::where('is_recommend', 1)->where('status', 1)->select('id', 'name', 'desc', 'tip', 'price', 'image')->get();
    }

    public function getSortList($limit)
    {
        return Product::where('status', 1)->orderBy('sales', 'desc')->limit($limit)->select('name', 'image', 'sales')->get();
    }

}
